import { Component, EventEmitter, Input, OnDestroy, OnInit, Output } from '@angular/core';
import { Subscription } from 'rxjs';
import { AssemblyDrawingViewService } from '@core/services/assemblyDrawing/assemblyDrawing.view.service';
import { AssemblyDrawingService } from '@core/services/assemblyDrawing/assemblyDrawing.service';
import { ApiService } from '@core/services/http/api.service';
import { forEach } from '@ag-grid-community/core/dist/cjs/utils/array';
import { ApesPreviewDialogComponent } from '@shared/ag-grid-ext/upload-component/apes-previewDialog.component';
import { ApesModalService } from '@shared/apes/modal';
import { deepClone } from '../../../utils/utils';
import { UserAuthService } from '@core/services/user-auth.service';
import { ApesMessageService } from '@shared/apes/message';

@Component({
  templateUrl: './cad-search-content.component.html',
  selector: 'cad-search-content',
  // styleUrls: ['./cad-search-content.component.scss'],
})

export class CadSearchContentComponent implements OnInit, OnDestroy {

  @Output() pageIndex = new EventEmitter<any>();
  @Output() sanTouPageIndex = new EventEmitter<any>();
  @Output() selected = new EventEmitter();
  @Output() errorParts = new EventEmitter();
  @Output() blackPage = new EventEmitter();
  @Output() stockChange = new EventEmitter();
  @Output() tagChange = new EventEmitter();
  @Output() tagPageIndex = new EventEmitter<any>();
  @Output() filterChange = new EventEmitter();


  _partsTag: any[] = [];
  _baseData: any = {};

  @Input()
  set partsTag(value: any) {
    this._partsTag = value;
  }

  get partsTag() {
    return this._partsTag;
  }

  @Input()
  set baseData(value: any) {
    this._baseData = value;
  }

  get baseData() {
    return this._baseData;
  }

  @Input() showTagMore;
  @Input() publicPage: boolean = false;
  @Input() shoppingData: any[] = [];
  @Input() showHidden: boolean = false;

  items: any[] = [];
  loading: boolean = false;

  matchData: any[] = [];
  matchLoading: boolean = false;
  // total: any = 0;
  // nowPage: any = 1;
  // pageSize: any = 20;
  matchPagination: any = {
    total: 0,
    pageSize: 10,
    currentPage: 1,
  };

  commonData: any[] = [];
  commonLoading: boolean = false;
  commonPagination: any = {
    total: 0,
    pageSize: 10,
    currentPage: 1,
  };

  priceData: any[] = [];
  priceLoading: boolean = false;
  priceTableCol: any[] = [];
  priceTableInit: any[] = [
    {
      type: 'Whole',
      col: [
        { style: '12%', name: '标准名称', key: 'category' },
        { style: '12%', name: '商品名称', key: 'name' },
        { style: '12%', name: '品牌', key: 'spBrand' },
        { style: '12%', name: '零件号', key: 'pn' },
        { style: '12%', name: '产品描述', key: 'describe' },
        { style: '12%', name: '成本价', key: 'notTaxUnitPrice' },
        { style: '12%', name: '建议售价', key: 'priceSuggested' },
        { style: '11%', name: '供应商', key: 'supplier' },
        { style: '5%', name: '操作', key: 'operation' },
      ],
    },
    {
      type: 'Accumulator',
      col: [
        { style: '12%', name: '标准名称', key: 'category' },
        { style: '12%', name: '品牌', key: 'spBrand' },
        { style: '12%', name: '国际标号', key: 'international' },
        { style: '12%', name: '参考号', key: 'reference' },
        { style: '12%', name: '产品描述', key: 'describe' },
        { style: '12%', name: '成本价', key: 'notTaxUnitPrice' },
        { style: '12%', name: '建议售价', key: 'priceSuggested' },
        { style: '11%', name: '供应商', key: 'supplier' },
        { style: '5%', name: '操作', key: 'operation' },
      ],
    },
    {
      type: 'Oily',
      col: [
        { style: '10%', name: '品牌', key: 'spBrand' },
        { style: '8%', name: '粘度等级', key: 'viscosityClass' },
        { style: '10%', name: 'API等级', key: 'apiClass' },
        { style: '10%', name: '机油类型', key: 'type' },
        { style: '10%', name: '系列', key: 'catena' },
        { style: '8%', name: '容量[L]', key: 'capacity' },
        { style: '10%', name: '产品描述', key: 'describe' },
        { style: '10%', name: '成本价', key: 'notTaxUnitPrice' },
        { style: '10%', name: '建议售价', key: 'priceSuggested' },
        { style: '9%', name: '供应商', key: 'supplier' },
        { style: '5%', name: '操作', key: 'operation' },
      ],
    },
    {
      type: 'Tyre',
      col: [
        { style: '10%', name: '品牌', key: 'spBrand' },
        { style: '8%', name: '规格', key: 'specification' },
        { style: '10%', name: '花纹', key: 'figure' },
        { style: '10%', name: '载重指数', key: 'loadIndex' },
        { style: '10%', name: '速度等级', key: 'speedClass' },
        { style: '8%', name: '是否防爆', key: 'antiExplosion' },
        { style: '10%', name: '产品描述', key: 'describe' },
        { style: '10%', name: '成本价', key: 'notTaxUnitPrice' },
        { style: '10%', name: '建议售价', key: 'priceSuggested' },
        { style: '9%', name: '供应商', key: 'supplier' },
        { style: '5%', name: '操作', key: 'operation' },
      ],
    },
  ];

  intelligentData: any[] = [];
  intelligentLoading: boolean = false;

  sanTouData: any[] = [];
  sanTouLoading: boolean = false;
  sanTouPagination: any = {
    total: 0,
    pageSize: 10,
    currentPage: 1,
  };

  isVisible: boolean = false;
  remark: any = '';
  correctionData: any;
  correctionList: any[] = [];

  heatMapData: any = [];                     // 当前热点图数据
  showMatch: boolean = true;
  showMatchDisplay: boolean = true;
  showPriceDisplay: boolean = true;
  showSanTou: boolean = true;
  showIntelligent: boolean = true;
  showIntelligentDisplay: boolean = true;
  queryStock: boolean = true;

  showFilter: boolean = false;
  filterData: any[] = [];
  showFilterData: any[] = [];
  moreFilterData: any[] = [];
  filterResultData: any[] = [];
  searchLoading: boolean = false;

  showTab: any = 'match';
  showCommon: boolean = false;

  private subscription: Subscription;
  private priceSubscription: Subscription;
  private sanTouInquireSubscription: Subscription;
  private sanTouPriceSubscription: Subscription;
  private pageSubscription: Subscription;
  private loadingSubscription: Subscription;
  private matchLoadingSubscription: Subscription;
  private priceLoadingSubscription: Subscription;
  private sanTouInquireLoadingSubscription: Subscription;
  private intelligentLoadingSubscription: Subscription;
  private showSubscription: Subscription;
  private showFilterSubscription: Subscription;

  constructor(
    private apiService: ApiService,
    private assemblyDrawingViewService: AssemblyDrawingViewService,
    private assemblyDrawingService: AssemblyDrawingService,
    private modalService: ApesModalService,
    private userAuthService: UserAuthService,
    private msg: ApesMessageService,
  ) {

  }

  ngOnInit(): void {

    this.loadingSubscription = this.assemblyDrawingViewService.searchLoadingBtn$.subscribe((data: boolean) => {
      this.searchLoading = data;
      if (data) {
        this.matchData = [];
        this.intelligentData = [];
        this.showFilter = false;
        this.filterData = [];
        this.showFilterData = [];
        this.moreFilterData = [];
        this.filterResultData = [];
        this.showCommon = false;
        this.showTab = 'match';
      }
    });


    this.matchLoadingSubscription = this.assemblyDrawingViewService.searchMatchLoadingBtn$.subscribe((data: boolean) => {
      if (data) {
        this.matchData = [];
        this.matchPagination.currentPage = 1;
        this.commonData = [];
        this.commonPagination.currentPage = 1;
      }
      this.matchLoading = data;
      this.commonLoading = data;
    });

    this.priceLoadingSubscription = this.assemblyDrawingViewService.searchPriceLoadingBtn$.subscribe((data: boolean) => {
      if (data) {
        this.priceData = [];
      }
      this.priceLoading = data;
    });

    this.sanTouInquireLoadingSubscription = this.assemblyDrawingViewService.searchSanTouInquireLoadingBtn$.subscribe((data: boolean) => {
      if (data) {
        this.sanTouPagination.currentPage = 1;
        this.sanTouData = [];
      }
      this.sanTouLoading = data;
    });


    this.intelligentLoadingSubscription = this.assemblyDrawingViewService.searchIntelligentLoadingBtn$.subscribe((data: boolean) => {
      if (data) {
        this.intelligentData = [];
      }
      this.intelligentLoading = data;
    });

    this.priceSubscription = this.assemblyDrawingViewService.searchPriceChange$.subscribe((data: any) => {
      console.log(data);
      if (data.hasOwnProperty('content')) {
        let type = data.type;
        this.priceTableInit.forEach((table) => {
          if (table.type == type) {
            this.priceTableCol = table.col;
          }
        });
        this.priceData = data.content;
      }
    });

    this.sanTouInquireSubscription = this.assemblyDrawingViewService.searchSanTouInquireChange$.subscribe((data: any) => {
      // console.log(data);
      if (data) {
        this.sanTouData = data['content'];
        this.sanTouPagination.total = data['total'];
        this.sanTouPagination.currentPage = data['page'] + 1;
      }
    });

    this.sanTouPriceSubscription = this.assemblyDrawingViewService.searchSanTouPriceChange$.subscribe((data: any) => {
      // console.log(data);
      if (data && data['content'].length != 0) {
        this.sanTouData.forEach((item) => {
          data['content'].forEach((d) => {
            if (item['productNumber'] == d['productNumber']) {
              item['priceSuggested'] = d['priceSuggested'];
            }
          });
        });
      }
    });


    this.subscription = this.assemblyDrawingViewService.searchDataChange$.subscribe((data: any) => {
      // console.log(data);
      if (data) {
        if (data.hasOwnProperty('apes')) {
          this.integrationMatchData(data);
        }
        if (data.hasOwnProperty('data')) {
          this.integrationIntelligentData(data);
        }
        if (data.hasOwnProperty('price')) {
          this.priceData = data.price.content;
          let type = data.price.type;
          this.priceTableInit.forEach((table) => {
            if (table.type == type) {
              this.priceTableCol = table.col;
            }
          });
        }
        if (data.hasOwnProperty('sanTou')) {
          this.sanTouData = data.sanTou.content;
          this.sanTouPagination.total = data.sanTou['total'];
          this.sanTouPagination.currentPage = data.sanTou['page'] + 1;
        }
      } else {
        this.matchData = [];
        this.intelligentData = [];
        this.priceData = [];
        this.sanTouData = [];
        this.showCommon = false;
      }
    });

    this.pageSubscription = this.assemblyDrawingViewService.searchPageDataChange$.subscribe((data: any) => {
      this.integrationMatchData(data);
      this.matchLoading = false;
    });

    this.showSubscription = this.assemblyDrawingViewService.showSearchIntelligent$.subscribe((data: any) => {
      this.showIntelligent = data == 'no_auto' || data == 'blurry';
      this.showMatch = data != 'blurry';
    });

    this.showFilterSubscription = this.assemblyDrawingViewService.searchFilterDataChange$.subscribe((data: any) => {
      this.showFilter = true;
      this.checkFilterData(data);
    });
  }

  ngOnDestroy(): void {
    this.subscription.unsubscribe();
    this.pageSubscription.unsubscribe();
    this.loadingSubscription.unsubscribe();
    this.matchLoadingSubscription.unsubscribe();
    this.intelligentLoadingSubscription.unsubscribe();
    this.showSubscription.unsubscribe();
    this.showFilterSubscription.unsubscribe();
    this.priceSubscription.unsubscribe();
    this.sanTouInquireSubscription.unsubscribe();
    this.sanTouInquireLoadingSubscription.unsubscribe();
    this.sanTouPriceSubscription.unsubscribe();
  }

  integrationMatchData(data) {
    this.showMatchDisplay = data['apesDisplay'] ? data['apesDisplay'] : data['display'];
    this.queryStock = data['queryStock'];
    if (this.showMatchDisplay) {

      if (data['queryStock']) {
        this.matchData = data.apes['content'];
        this.matchData.forEach((data) => {
          data['loading'] = false;
        });
        this.matchPagination.total = data.apes['total'];
        this.matchPagination.currentPage = data.apes['page'] + 1;
      } else {
        this.commonData = data.apes['content'];
        this.commonData.forEach((data) => {
          data['loading'] = false;
        });
        this.commonPagination.total = data.apes['total'];
        this.commonPagination.currentPage = data.apes['page'] + 1;
      }
    } else {
      this.matchData = [];
      this.commonData = [];
    }
  }

  integrationIntelligentData(data) {
    this.showIntelligentDisplay = data['dataDisplay'] ? data['dataDisplay'] : data['display'];
    this.intelligentData = data.data['items'];
    this.intelligentData.forEach((data) => {
      data['imageSN'] = data['sn'];
      data['quantity'] = data['qty'];
      data['loading'] = false;
      data['orderQuantity'] = 1;
    });
  }

  filterName(value) {
    let name = '';
    if (value) {
      name = value.replace(/\$\$/g, ' ');
    }
    return name;
  }

  showPrice(data, tr) {
    let key = tr.key;
    let show;
    if (key == 'spBrand') {
      show = data[key].name;
    } else {
      show = data[key];
    }
    if (!this.showHidden && (key == 'notTaxUnitPrice' || key == 'priceSuggested')) {
      show = '--';
    }
    return show;
  }

  showStock(data) {
    if (data.hasOwnProperty('area') || data.hasOwnProperty('general')) return;
    let api = 'fn.service.findStockByProduct';
    let setData = {
      condition: data,
      conditionModel: this.assemblyDrawingService.modelData,
      custom: this._baseData.custom,
    };
    this.apiService.post(api, setData).subscribe((body) => {
      // console.log(body);
      if (body) {
        data['area'] = body['area'];
        data['general'] = body['general'];
      }
    });
  }

  getStockAmountTooltipFormatter(data) {
    let show =
      '门店实际库存：' + data.usableQTY + '<br/>' +
      '服务单确认未领料库存：-' + data.frozenQTY + '<br/>' +
      '转储收货在途：' + data.transferReceiveQty + '<br/>' +
      '订货在途：' + data.purchasingWayQty + '<br/>' +
      '转入制单数：' + data.transferInBillingQty + '<br/>' +
      '要货数：' + data.requireBillingQty;
    return show;

  }

  getStockTooltipFormatter(data, type) {
    let show = '加载中...';
    if (data.hasOwnProperty(type)) {
      let text = '';
      data[type].forEach((res) => {
        if (res.hasOwnProperty('companyId')) {
          text += '[' + res.companyId + ']' + res.companyName + '<br/>'
            + '- 库存：' + res.stock + '<br/>';
          // + '- 参考成本：' + res.referTax + '<br/>';
        } else if (res.hasOwnProperty('stockType')) {
          text += '- ' + res.stockType + '：' + res.stock + '<br/>';
        }
      });
      show = text;
    }
    return show;
  }

  showHighLightText(data, type) {
    let name;
    if (data.hasOwnProperty('highLightText') && data.highLightField == type) {
      name = this.filterName(data.highLightText);
    } else {
      name = this.filterName(data[type]);
    }
    return name;
  }


  showPartsName(value) {
    let name = '';
    if (value && value.length != 0) {
      if (value.length == 1) {
        name = value[0]['PJMC'];
      } else {
        for (let i = 0; i < value.length; i++) {
          if (i == value.length - 1) {
            name += value[i]['PJMC'];
          } else {
            name += (value[i]['PJMC'] + '; ');
          }
        }
      }
    }
    return name;
  }

  pageIndexChange($event, common = true) {
    let index = $event - 1;
    this.pageIndex.emit({ page: index, queryStock: common });
    if (common) {
      this.matchLoading = true;
      this.matchPagination.currentPage = $event;
    } else {
      this.commonLoading = true;
      this.commonPagination.currentPage = $event;
    }
  }

  sanTouPageIndexChange($event) {
    let index = $event - 1;
    this.sanTouPagination.currentPage = $event;
    this.sanTouPageIndex.emit(index);
    this.sanTouLoading = true;
  }

  showScroll() {
    let height = '55vh'; // 60vh
    // if (this.matchData.length != 0 && this.intelligentData.length != 0) {
    //   height = '25vh';
    // }
    // if (this.showFilter) {
    //   height = '40vh';
    // }
    return { y: height };
  }

  showState(value) {
    switch (value) {
      case '0':
        return '正常';

      case '2':
        return '停产下市';

      case '3':
        return '停用';

      case '5':
        return '预上市';
    }
  }

  showStatus(status) {
    switch (status) {
      case 'init':
        return false;

      case 'change':
        return false;

      case 'loading':
        return true;

      case 'end':
        return true;
    }
  }

  showImg(data) {
    if (data.sn == '') return;
    this.heatMapData = [];

    data['id'] = data['subGroupId'];
    this.assemblyDrawingService.baseData['mainGroupId'] = data['mainGroupCode'];
    this.assemblyDrawingService.baseData['mainSelectorId'] = data['selectorId'];
    this.assemblyDrawingService.searchImgPointParts(data, (res) => {
      if (res) {
        this.heatMapData['imgs'] = res.imgs;
        let urls = [];
        if (data.hasOwnProperty('imageSN')) {
          urls = this.filterImgData(data['imageSN']);
        }

        let option = {
          title: '预览图片',
          _fileList: urls,
          idName: 'showImg',
        };

        this.openUploadDialog(option, (result: any) => {
        });
      }
    });

  }

  openUploadDialog(option: any, callback: any, dialog?: any) {

    let body: any = { ...option };

    const openDialog = dialog ? dialog : ApesPreviewDialogComponent;
    const dialogRef = this.modalService.create({
      apesWidth: '45vw',
      apesTitle: body.title,
      apesContent: openDialog,
      apesComponentParams: body,
      apesFooter: [
        {
          label: '取消',
          type: 'default',
          onClick: (componentInstance) => {
            dialogRef.destroy(componentInstance['fileList']);
          },
        },
        {
          label: '确定',
          type: 'primary',
          onClick: (componentInstance) => {
            dialogRef.destroy(componentInstance['fileList']);
          },
        },
      ],
    });

    return dialogRef.afterClose.subscribe((result) => callback(result));
  }

  // 处理热点图数据
  filterImgData(sn) {
    let _sn = sn.replace(/[()]/g, '');
    let urls = [];

    if (this.heatMapData['imgs'].length != 0) {
      this.heatMapData['imgs'].forEach((img) => {
        let points = [];
        img['points'].forEach((p) => {
          if (p['sn'] == _sn) {
            points.push(p);
          }
        });

        if (points.length == 0) return;

        let name = this.interceptionName(img['url']);
        let url = {
          'fileName': name,
          'size': 0,
          'name': name,
          'id': '',
          'type': 'image/jpeg',
          'url': img['url'],
          'points': points,
        };
        urls.push(url);
      });
    }

    return urls;
  }

  // 处理热点图名称
  interceptionName(name) {
    let arr = name.split('/');
    let res = arr[arr.length - 1];
    return res;
  }

  orderMatchParts(e, data) {
    e.stopPropagation();
    console.log('添加进购物车', data);

    let setData = {
      condition: data,
      conditionModel: this.assemblyDrawingService.modelData,
      custom: this._baseData.custom,
    };

    data.loading = true;
    // fn.service.getPrise cm.product.assemblyDrawingProductPrice
    this.apiService.post('cm.product.assemblyDrawingProductPrice', setData).subscribe((res) => {
      if (res) {
        res['partCode'] = res.product.id;
        res['partName'] = res.product.name;
        res['parts'] = [{
          'PJMC': res.product.category.name,
        }];
        res['isMatchParts'] = false;
        res['orderQuantity'] = 1;
        this.selected.emit(res);
      }

      data.loading = false;
    });

  }

  orderPriceParts(e, data) {
    e.stopPropagation();
    console.log('添加进购物车', data);
    let check = false;
    let quantity = data.quantity;
    if (data.hasOwnProperty('source') && data.source == 'santou') {
      check = true;
    }

    let setData = {
      condition: data,
      conditionModel: this.assemblyDrawingService.modelData,
      custom: this._baseData.custom,
    };

    data.loading = true;
    this.apiService.post('fn.priceForwardService.addToShoppingCart', setData).subscribe((res) => {
      console.log(res);
      if (res) {
        // res['partCode'] = res.product.id;
        // res['partName'] = res.product.name;
        // res['parts'] = [{
        //   'PJMC': res.product.category.name,
        // }];
        res['isMatchParts'] = false;
        res['orderQuantity'] = 1;
        this.selected.emit(res);

        if (check) {
          let sum = this.checkShopData(data);
          if (sum > quantity) {
            this.msg.error('已超出当前最大库存数，可考虑选择其他渠道添加商品!');
          }
        }
      }

      data.loading = false;
    });

  }

  orderParts(e, data) {
    e.stopPropagation();
    // console.log('添加进购物车', data);

    data.loading = true;
    data['id'] = data['subGroupId'];
    this.assemblyDrawingService.baseData['mainGroupId'] = data['mainGroupCode'];
    this.assemblyDrawingService.baseData['mainSelectorId'] = data['selectorId'];
    this.assemblyDrawingService.searchAddPartsList(data, (res) => {
      if (res) {
        let partsData = res['PartsData'];
        let imgData = res['ImgData'];
        for (let i = 0; i < partsData.length; i++) {
          let listData = partsData[i];
          if (listData.imageSN && listData.imageSN == data.imageSN && listData.partCode != data.partCode) {
            // this.msg.info('该配件存在高低配，请注意选件',{apesDuration: 3000});
            data['highLowconfig'] = true;
            break;
          }
        }
        this.selected.emit(data);
      }

      data.loading = false;
    });

  }

  clickStar(data) {
    let userInfoModel = this.userAuthService.getUserInfoObj();
    let setData = {
      U_ID: userInfoModel.userAccount.userId,
      product: data.id,
    };
    this.apiService.post('fn.service.createStarProduct', setData).subscribe((res) => {

    });
    if (data.star > 0) {
      data.star = 0;
    } else {
      data.star = 1;
    }
  }

  handleCancel() {
    this.isVisible = false;
    this.correctionData = null;
    this.remark = '';
  }

  handleOk() {
    // console.log(this.remark);
    let data = {
      ...this.correctionData,
      remark: this.remark,
    };
    this.isVisible = false;
    this.correctionData['parts'] = [];
    this.correctionList.push(data);
    this.errorParts.emit(data);
    this.remark = '';
    this.correctionData = null;
  }

  errorCorrection(e, data) {
    e.stopPropagation();
    this.isVisible = true;
    this.correctionData = data;
  }

  selectPart(part) {
    // console.log(part);
    part['id'] = part['subGroupId'];
    this.assemblyDrawingService.baseData['mainGroupId'] = part['mainGroupCode'];
    this.assemblyDrawingService.baseData['mainSelectorId'] = part['selectorId'];
    this.assemblyDrawingViewService.mainMenuChange$.next({ name: part['mainGroupName'] });
    this.assemblyDrawingViewService.subMenuChange$.next({ name: part['subGroupName'] });
    this.assemblyDrawingViewService.subgroupChange$.next([]);
    this.assemblyDrawingService.searchPartsList(part);
  }


  back() {
    this.blackPage.emit(3);
  }

  searchStock() {
    this.commonLoading = true;
    this.stockChange.emit({ page: 0, queryStock: false });
  }

  showCommonTab() {
    this.showCommon = true;
  }

  partsTagMore() {
    this.tagPageIndex.emit();
  }

  tagCheck(parts) {
    if (this.searchLoading) return;
    this._partsTag.forEach((p) => {
      p.checked = p.id == parts.id;
    });
    this.tagChange.emit();
  }

  showListItem(type) {
    let show = true;
    if (type == 'match') {
      show = this.showMatch
        && this.showStatus(this._baseData.status)
        && this._baseData.hasBelongDept
        && this.showMatchDisplay;
    } else if (type == 'intelligent') {
      show = this.showIntelligent
        && this.showStatus(this._baseData.status)
        && this._baseData.isQuery
        && this.showIntelligentDisplay;
    } else if (type == 'price') {
      show = this.showPriceDisplay
        && this.priceData.length != 0
        && this.showStatus(this._baseData.status);
    } else if (type == 'sanTou') {
      show = this.showSanTou
        && this.sanTouData.length != 0
        && this.showStatus(this._baseData.status);
    }
    return show;
  }

  checkFilterData(data) {
    this.showFilterData = [];
    this.moreFilterData = [];
    this.filterData = data;
    let showMore = 4;
    let showData = [];
    let moreData = [];
    if (data.length > showMore) {
      for (let i = 0; i < showMore; i++) {
        data[i]['showMore'] = true;
        data[i]['multiple'] = false;
        showData.push(data[i]);
      }
      this.showFilterData = showData;
      for (let i = showMore; i < data.length; i++) {
        moreData.push(data[i]);
      }
      this.moreFilterData = moreData;
    } else {
      this.showFilterData = data;
    }
  }

  showMoreBtn(data) {
    data.showMore = !data.showMore;
    if (data.showMore) {
      data.multiple = false;
    }
  }

  showMultipleBtn(data) {
    data.multiple = !data.multiple;
    if (data.multiple) {
      data.showMore = false;
    } else {
      data.showMore = true;
    }
  }

  selectFilterData(data, index?, common = true) {
    let setData = deepClone(data);
    setData.values = [];
    if (index != null) {
      setData.values.push(data.values[index]);
    } else {
      this.showMultipleBtn(data);
      data.values.forEach((res) => {
        if (res.hasOwnProperty('checked') && res.checked) {
          setData.values.push(res);
        }
      });
    }
    this.filterResultData.push(setData);
    this.resetFilterData();
    this.matchLoading = true;
    this.filterChange.emit({ data: this.filterResultData, queryStock: common });
  }

  clearResultData(index, common = true) {
    this.filterResultData.splice(index, 1);
    this.resetFilterData();
    this.matchLoading = true;
    this.filterChange.emit({ data: this.filterResultData, queryStock: common });
  }

  resetFilterData() {
    this.showFilterData = [];
    this.moreFilterData = [];
    let data = [];
    let resultData = deepClone(this.filterResultData);
    let showMore = 4;
    let showData = [];
    let moreData = [];
    this.filterData.forEach((filterData) => {
      let check = true;
      resultData.forEach((res) => {
        if (res.key == filterData.key) {
          check = false;
        }
      });
      if (check) {
        data.push(filterData);
      }
    });

    if (data.length > showMore) {
      for (let i = 0; i < showMore; i++) {
        data[i]['showMore'] = true;
        data[i]['multiple'] = false;
        showData.push(data[i]);
      }
      this.showFilterData = showData;
      for (let i = showMore; i < data.length; i++) {
        moreData.push(data[i]);
      }
      this.moreFilterData = moreData;
    } else {
      this.showFilterData = data;
    }
  }

  checkShopData(param) {
    // console.log(param);
    let num = 0;
    if (this.shoppingData.length != 0) {
      this.shoppingData.forEach((shopData) => {
        if (param.id == shopData.id || param.id == shopData.innerBusinessKey) {
          num = shopData.orderQuantity;
        }
      });
    }
    return num;
  }

  checkShowTab(tab) {
    // return this.showTab == tab;
    return true;
  }

  checkTabs(tab) {
    // console.log('切换--', tab);
    // this.showTab = tab;
    if (tab == 'common' && this.commonData.length == 0) {
      this.searchStock();
    }
  }
}
